Do not fail sampling completely if a single thread dies before sampling - #771
Merged
benfred merged 2 commits intoJul 13, 2025
Merged
Conversation
Contributor
Author
|
I have a stress test lying around with: import threading
import os
print(os.getpid())
def _dummy():
#time.sleep(0.1)
pass
for index in range(0, 100_000):
if index % 1000 == 0:
print("Iteration: ", index)
ts = []
for i in range(0, 10):
t = threading.Thread(target=_dummy)
ts.append(t)
t.start()
for t in ts:
t.join()
print("HEY")If you record this with ETA: With this patch and my remoteprocess change, it is ~1%. |
benfred
approved these changes
Jul 13, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The flow when sampling a process starts by
/proc/pid/task/<tid>./proc/<tid>/stat.During this time, we did not suspend the process yet. Therefore, it might happen that a thread dies precisely in the milliseconds between the enumeration readdir and the stat for active checking. In those cases, py-spy bails out completely, skipping all threads. If a process creates a lot of threads and tears them down (e.g. through using some native dependency with a saner threading model, such as rust with polars), this case can be hit a lot.
I do not see why we would want to throw out a full sample, just because a single thread died prematurely. Therefore, I propose silently ignoring stat errors for threads. The
.threads()method will re-enumerate and find the thread lacking, if it is called in later parts of the code.Doing this also exposed benfred/remoteprocess#106.
Even without this patch, sampling might fail with
EPERM, but that is an expected quirk of ptrace: https://elixir.bootlin.com/linux/v6.15.3/source/kernel/ptrace.c#L458 if the process is currently exiting, ptrace returnsEPERMinstead ofESRCH.